package com.wisdytech.linkdcs.linkdcsservicepad.common.UtilMapper;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wisdytech.app.quality.dao.SerialNumberDao;
import com.wisdytech.app.quality.dao.SysCodeDefDetailDao;
import com.wisdytech.app.quality.dao.SysCodeDefinitionDao;
import com.wisdytech.linkdcs.linkdcsservicepad.common.exception.BaseException;
import com.wisdytech.linkdcs.pad.model.SerialNumber;
import com.wisdytech.linkdcs.pad.model.SysCodeDefDetail;
import com.wisdytech.linkdcs.pad.model.SysCodeDefinition;
import com.wisdytech.linkdcs.system.dao.ISysDictDao;
import com.wisdytech.linkdcs.system.model.SysDict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service("commonMapper")
@Transactional
public class CommonMapper {

    /**
     * 最小流水号，1
     */
    private static final int MIN_VALUE = 1;
    @Resource
    private SysCodeDefinitionDao sysCodeDefinitionDao;
    @Resource
    private SysCodeDefDetailDao sysCodeDefDetailDao;
    @Resource
    private ISysDictDao sysDictDao;
    @Resource
    private SerialNumberDao serialNumberDao;

    public String createCodeDef(String codeName, String materialModel, String lineTag, String supplierTag){
        Date currentDate = new Date();
        String batchNo = "";
        SysCodeDefinition codeDef;
        SysCodeDefinition code = new SysCodeDefinition();
        code.setCodeName(codeName);
        codeDef = this.sysCodeDefinitionDao.selectOne(code);
        if(codeDef == null){
            //批次编码规则未定义
            throw new BaseException("编码规则未定义！") ;
        }

        List<SysCodeDefDetail> codeList;
        EntityWrapper<SysCodeDefDetail> ew = new EntityWrapper();
        ew.eq("CODE_DEF_ID",codeDef.getPkId());
        ew.orderBy("SERIAL_NUM");
        codeList = this.sysCodeDefDetailDao.selectList(ew);
        //如果间隔符为3，标识没有间隔
        String fillingStr = "3".equals(codeDef.getSpacer()) ? "" : this.getDictValueByKey("SPACE_MARK", codeDef.getSpacer());
        for (SysCodeDefDetail codeDefDetail : codeList) {
            //编码类型为固定编码
            if("1".equals(codeDefDetail.getSegmentType())){
                batchNo += codeDefDetail.getSegmentContent();
            }
            //编码类型为动态编码
            if("2".equals(codeDefDetail.getSegmentType())){
                //物料型号标识
                if("10".equals(codeDefDetail.getSegmentCategory())){
                    batchNo += materialModel;
                }
                //产线标识
                if("11".equals(codeDefDetail.getSegmentCategory())){
                    batchNo += lineTag;
                }
                //供应商标识
                if("12".equals(codeDefDetail.getSegmentCategory())){
                    batchNo += supplierTag;
                }
            }
            //编码类型为日期
            if("3".equals(codeDefDetail.getSegmentType())){
                SimpleDateFormat sdf;
                sdf = new SimpleDateFormat(this.getDictValueByKey("DATE_FORMAT", codeDefDetail.getDateFormat()));
                batchNo += sdf.format(currentDate);
            }
            //编码类型为序号
            if("4".equals(codeDefDetail.getSegmentType())){
                int serialNo;
                serialNo = getCurrentSerialNo(batchNo);
                DecimalFormat df;
                String fmtStr = "";
                for(int i = 0; i < codeDefDetail.getSegmentLength(); i ++){
                    fmtStr += "0";
                }
                df = new DecimalFormat(fmtStr);
                batchNo += df.format(serialNo);
            }
            batchNo += fillingStr;
        }

        if(batchNo.isEmpty()){
            return null;
        }
        if(fillingStr.isEmpty()){
            return batchNo;
        }
        return batchNo.substring(0, batchNo.length() - 1);
    }

    private int getCurrentSerialNo(String batchNo) {
        EntityWrapper<SerialNumber> ew = new EntityWrapper();
        ew.eq("PRO_CODE",batchNo);
        List<SerialNumber> list = serialNumberDao.selectList(ew);
//        if(list.isEmpty()){
//            SerialNumber number = new SerialNumber();
//            number.setProCode();
//            number.setSerialNumber();
//            this.insertSerialNumber(proCode, MIN_VALUE);
//            return MIN_VALUE;
//        }
//        this.updateSerialNumber(proCode);
        return Integer.parseInt(String.valueOf(list.get(0).getSerialNumber())) + 1;
    }

    private String getDictValueByKey(String parentKey, String dictKey) {
        EntityWrapper<SysDict> ew = new EntityWrapper();
        ew.eq("PARENT_KEY",parentKey);
        ew.eq("DICT_KEY",dictKey);
        List<SysDict> list;
        list = this.sysDictDao.selectList(ew);
        if (!list.isEmpty()) {
            return list.get(0).getDictValue();
        }
        return null;
    }
}
